
package com.yyf.springboot2.common;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.apache.commons.codec.binary.Base64;

import java.util.HashMap;
import java.util.Map;

/**
 * 前后端数据传输加密工具类
 * @author monkey
 *
 */
public class AuthToken {
	//可配置到Constant中，并读取配置文件注入,16位,自己定义
	private static final String KEY = "xxxxxxxxxxxxxxxx";

	//参数分别代表 算法名称/加密模式/数据填充方式
	private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";

	/**
	 * 加密
	 * @param content 加密的字符串
	 * @param encryptKey key值
	 * @return
	 * @throws Exception
	 */
	public static String encrypt(String content, String encryptKey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128);
		Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
		cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptKey.getBytes(), "AES"));
		byte[] b = cipher.doFinal(content.getBytes("utf-8"));
		// 采用base64算法进行转码,避免出现中文乱码
		return Base64.encodeBase64String(b);

	}

	/**
	 * 解密
	 * @param encryptStr 解密的字符串
	 * @param decryptKey 解密的key值
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encryptStr, String decryptKey) throws Exception {
		KeyGenerator kgen = KeyGenerator.getInstance("AES");
		kgen.init(128);
		Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
		cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
		// 采用base64算法进行转码,避免出现中文乱码
		byte[] encryptBytes = Base64.decodeBase64(encryptStr);
		byte[] decryptBytes = cipher.doFinal(encryptBytes);
		return new String(decryptBytes);
	}

	/**
	 * 根据用户id，ip，登录时间进行加密、登录时间可为空
	 * @param content uid，ip，time    String content = text+"|"+text2+"|"+text3;
	 *   KEY：约定的密钥
	 * @return  token
	 * @throws Exception
	 */
	public static String encrypt(String content) throws Exception {
		String token = 	encrypt(content, KEY);
		return token;
	}
	//指定获取的信息
	public static String decrypt(String encryptStr,Integer type) throws Exception {
		String[] info = decrypt(encryptStr, KEY).split("\\|");
		if (info.length!=3){
			throw new Exception("ERROR:Token不合法");
		}
		if (type==null){
			throw new Exception("ERROR:type不能为空");
		}
		switch (type) {
			case 0:
				return info.toString();
			case 1:
				return info[0];
			case 2:
				return info[1];
			case 3:
				return info[2];
			default:
				throw new Exception("ERROR:type值范围错误(1-3)");
		}

	}



}